<template>
	<view class="container">
		<!-- 订单列表 -->
		<view class="order-list">
			<!-- 空状态 -->
			<view class="empty-container" v-if="!loading && orders.length === 0">
				<text class="empty-text">暂无订单</text>
			</view>
			
			<view 
				class="order-card" 
				v-for="order in orders" 
				:key="order.id"
			>
				<!-- 订单时间 -->
				<view class="order-time">
					<text class="time-text">{{ order.time }}</text>
					<text class="order-status">{{ order.status }}</text>
				</view>
				
				<!-- 店铺名和下单人 -->
				<view class="order-info">
					<text class="info-text" v-if="order.storeName">{{ order.storeName }}</text>
					<text class="info-text" v-if="order.userName">{{ order.userName }}</text>
				</view>
				
				<!-- 订单商品 -->
				<view class="order-items" @click="goToOrderDetails(order)">
					<view 
						class="item-preview" 
						v-for="(item, index) in order.items" 
						:key="index"
					>
						<image class="item-image" v-if="item.image" :src="item.image" mode="aspectFill"></image>
						<image class="item-image" style="border:1px solid #f0f0f0;" v-else src="../common/images/noImage.png" mode="aspectFill"></image>
						<text class="item-name">{{ item.name }}</text>
					</view>
				</view>
				
				<!-- 订单总价和数量 -->
				<view class="order-summary">
					<view class="price-info">
						<text class="total-price">¥ {{ order.totalPrice }}
							<!-- <text class="pay-status" v-if="order.payStatus == 0">（计入欠款）</text>
							<text class="pay-status" v-if="order.payStatus == 1 && order.payMethodId == 0">（已支付）</text>
							<text class="pay-status" v-if="order.payStatus == 1 && order.payMethodId == 1">（已补交）</text>
							<text class="pay-status" v-if="order.payStatus == 2">（补交中）</text> -->
						</text>
						<text class="item-count">共{{ order.totalCount }}件</text>
					</view>
					<view class="action-btn-group" >
						<!-- 关闭 -->
						<view class="action-btn" v-if="order.orderStatus == 1" @click="updateOrderStatus(order.id,4)">
							<text class="btn-text">关闭</text>
						</view>
						<!-- 发货 -->
						<view class="action-btn" v-if="order.orderStatus == 1" @click="updateOrderStatus(order.id,2)">
							<text class="btn-text">发货</text>
						</view>
						<!-- 欠款审核 -->
						<view class="action-btn" v-if="order.payStatus == 2" @click="goToPay(order)">
							<text class="btn-text">欠款审核</text>
						</view>	
					</view>
				</view>
			</view>
		</view>
		
		<!-- 合计区域 -->
		<view class="total-bar" @click="showTotalDetail" v-if="orders && orders.length > 0">
			<view class="total-item">
				<text>订单总额：</text>
				<text class="value">¥{{ totalAmount }}</text>
			</view>
			<view class="total-item">
				<text>订单笔数：</text>
				<text class="value">{{ totalCount }}</text>
			</view>
		</view>
		
		<!-- 合计详情弹窗 -->
		<u-popup v-model="showDetail" mode="bottom" border-radius="20" v-if="orders && orders.length > 0">
			<view class="total-detail">
				<view class="detail-header">
					<text class="title">合计数据</text>
					<view class="close-btn" @click="showDetail = false">×</view>
				</view>
				<view class="detail-content">
					<view class="detail-item">
						<text class="label">订单总额：</text>
						<text class="value">¥{{ totalAmount }}</text>
					</view>
					<view class="detail-item">
						<text class="label">订单笔数：</text>
						<text class="value">{{ totalCount }}</text>
					</view>
					<view class="detail-item">
						<text class="label">商品总件数：</text>
						<text class="value">{{ totalQuantity }}</text>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			orders: [],
			allOrders: [], // 保存所有订单数据
			loading: false,
			orderStatus: '',
			payStatus: '',
			title: '',
			showDetail: false, // 合计详情弹窗显示状态
		}
	},
	computed: {
		// 计算订单总金额
		totalAmount() {
			if (this.orders && this.orders.length > 0) {
				return this.orders.reduce((sum, order) => {
					return sum + (parseFloat(order.totalPrice) || 0);
				}, 0).toFixed(2);
			}
			return '0.00';
		},
		// 计算订单笔数
		totalCount() {
			return this.orders ? this.orders.length : 0;
		},
		// 计算商品总件数
		totalQuantity() {
			if (this.orders && this.orders.length > 0) {
				return this.orders.reduce((sum, order) => {
					return sum + (order.totalCount || 0);
				}, 0);
			}
			return 0;
		}
	},
	onLoad(options) {
		if(options.orderStatus) {
			this.orderStatus = options.orderStatus
		}
		if(options.payStatus) {
			this.payStatus = options.payStatus
		}
		if(options.title) {
			this.title = options.title
			uni.setNavigationBarTitle({
				title: this.title
			})
		}
	},
	onShow() {
		// 页面显示时加载订单列表（包括首次进入和从其他页面返回）
		this.loadOrderList()
	},
	methods: {
		// 加载订单列表
		loadOrderList() {
			this.loading = true
			uni.showLoading({
				title: '加载中...',
				mask: true
			})
			
			this.$u.api.orderManagement.listByShop({
				orderStatus: this.orderStatus,
				payStatus: this.payStatus
			}).then(res => {
				uni.hideLoading()
				this.loading = false
				
				if (res && res.data) {
					// 保存所有订单
					this.allOrders = res.data.map(item => ({
						id: item.id,
						orderNo: item.orderNo,
						time: item.createDate || '',
						status: item.orderStatusName || '',
						orderStatus: item.orderStatus,
						items: (item.itemList || []).map(product => ({
							id: product.productId,
							name: product.productName || '',
							image: product.productImage || '',
							price: product.productPrice || 0,
							costPrice: product.productCostPrice || 0,
							quantity: product.quantity || 0
						})),
						totalPrice: item.totalAmount || 0,
						totalCostPrice: item.totalCostAmount || 0,
						totalCount: (item.itemList || []).reduce((sum, p) => sum + (p.quantity || 0), 0),
						storeName: item.shopName || '',
						receiverName: item.receiverName || '',
						receiverPhone: item.receiverPhone || '',
						receiverAddress: item.receiverAddress || '',
						receiveDate: item.receiveDate || '',
						remark: item.remark || '',
						payMethod: item.payMethod || '',
						payMethodId: item.payMethodId || 0,
						payStatus: item.payStatus,
						userName: item.userName || ''
					}))
					this.orders = this.allOrders
				} else {
					this.allOrders = []
					this.orders = []
				}
			}).catch(err => {
				uni.hideLoading()
				this.loading = false
				console.error('获取订单列表失败:', err)
				uni.showToast({
					title: '获取订单列表失败',
					icon: 'none'
				})
			})
		},
		goToOrderDetails(order) {
			uni.navigateTo({
				url: '/pages/inventoryManagement/orderDetails?order=' + JSON.stringify(order) + '&isAllOrder=true'
			})
		},
		updateOrderStatus(id,status) {
			// 确定要关闭此订单吗
			uni.showModal({
				title: '提示',
				content: status == 4 ? '确定要关闭此订单吗' : '确定要发货吗',
				success: (res) => {
					if (res.confirm) {
						this.updateOrderStatusToServer(id,status)
					}
				}
			})
		},
		updateOrderStatusToServer(id,status) {
			uni.showLoading({
				title: '操作中...',
				mask: true
			})
			this.$u.api.orderManagement.updateStatus({
				orderNo: id,
				orderStatus: status
			}).then(res => {
				if (res && res.result === 'true') {
					uni.showToast({
						title: '操作成功',
						icon: 'success'
					})
					this.loadOrderList()
				} else {
					uni.hideLoading()
					uni.showToast({
						title: res.message || '操作失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('操作失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			}).finally(() => {
				uni.hideLoading()
			})
		},
		goToPay(order) {
			uni.navigateTo({
				url: '/pages/inventoryManagement/payDebt?order=' + JSON.stringify(order) + '&isAllOrder=true'
			})
		},
		showTotalDetail() {
			this.showDetail = true;
		}
	},
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
	padding-bottom: 120rpx; /* 为底部合计栏留出空间 */
}

/* 订单列表 */
.order-list {
	flex: 1;
	padding: 20px;
}

/* 空状态 */
.empty-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80px 20px;
}

.empty-text {
	font-size: 14px;
	color: #999999;
	margin-top: 20px;
}

.order-card {
	background-color: #ffffff;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 15px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-status {
	font-size: 14px;
	color: #ff4069;
}

/* 订单时间 */
.order-time {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.time-text {
	font-size: 14px;
	color: #666666;
}

/* 店铺名和下单人 */
.order-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
	flex-wrap: wrap;
}

.info-text {
	font-size: 12px;
	color: #333333;
}

/* 订单商品 */
.order-items {
	max-height: 70px;
	overflow: hidden;
	display: flex;
	flex-wrap: wrap;
	gap: 15px;
	margin-bottom: 15px;
}

.item-preview {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.item-image {
	width: 40px;
	height: 40px;
	border-radius: 8px;
	background-color: #f0f0f0;
	margin-bottom: 5px;
}

.item-name {
	font-size: 10px;
	color: #333333;
}

/* 订单总价和数量 */
.order-summary {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.price-info {
	display: flex;
	flex-direction: column;
}

.total-price {
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 2px;
}

.pay-status {
	font-size: 10px;
	line-height: 14px;
	color: #ff4069;
}
.item-count {
	font-size: 10px;
	color: #333333;
}

.action-btn-group {
	display: flex;
	gap: 10px;
}

.action-btn {
	padding: 4px 8px;
	border: 1px solid #333333;
	border-radius: 20px;
}

.btn-text {
	font-size: 12px;
	color: #333333;
}

/* 合计区域 */
.total-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 88rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	z-index: 999;
}

.total-item {
	display: flex;
	align-items: center;
	font-size: 28rpx;
	color: #666;
}

.total-item .value {
	color: #333;
	font-weight: bold;
	margin-left: 10rpx;
}

.total-detail {
	width: 100%;
	background-color: #ffffff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
}

.detail-header {
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 30rpx;
	border-bottom: 1rpx solid #eee;
	position: relative;
}

.detail-header .title {
	font-size: 32rpx;
	color: #333;
}

.detail-header .close-btn {
	position: absolute;
	right: 30rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 48rpx;
	color: #999;
}

.detail-content {
	padding: 30rpx;
	max-height: 60vh;
	overflow-y: auto;
}

.detail-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.detail-item:last-child {
	border-bottom: none;
}

.detail-item .label {
	font-size: 28rpx;
	color: #666;
}

.detail-item .value {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}
</style>
